package com.xusheng.cli.controller.open;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xusheng.cli.common.base.MyPage;
import com.xusheng.cli.common.base.Result;
import com.xusheng.cli.common.tools.UnitConvertUtils;
import com.xusheng.cli.entity.dictionaryModule.Category;
import com.xusheng.cli.entity.favoritesModule.Favorites;
import com.xusheng.cli.entity.frontUserModule.FrontUser;
import com.xusheng.cli.entity.likesModule.Likes;
import com.xusheng.cli.entity.videoModule.Video;
import com.xusheng.cli.req.RankResp;
import com.xusheng.cli.req.VideoQueryReq;
import com.xusheng.cli.service.*;
import com.xusheng.cli.tools.CurrentPlayerUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 视频相关接口
 *
 * @author lyh
 * @since 2023-04-27 10:57
 */
@Slf4j
@RestController
@RequestMapping("/open/v1/video")
public class VideoController {

    @Resource
    private VideoService videoService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private FavoritesService favoritesService;
    @Resource
    private LikesService likesService;
    @Resource
    private FrontUserService frontUserService;
    @Resource
    private CommentService commentService;

    @Resource
    private DownloadStatisticsService downloadStatisticsService;
    @Resource
    private ProxyHostService proxyHostService;

    /**
     * 获取主页视频列表
     *
     * @return 返回结果
     */
    @GetMapping("/homeList")
    public Result<List<Video>> homeList() {
        MyPage<Video> page = videoService.lambdaQuery()
                .orderByDesc(Video::getCreateTime)
                .page(new MyPage<>(1, 24));
        page.getRecords().forEach(v -> {
            if (v.getSource() == 0) {
                v.setUrl(null);
            }
        });
        return Result.success(page.getRecords());
    }

    /**
     * 按条件查询
     *
     * @param req 查询条件
     * @return 返回结果
     */
    @GetMapping("/list")
    public Result<MyPage<Video>> list(VideoQueryReq req) {
        MyPage<Video> page = videoService.lambdaQuery()
                .eq(req.getCategoryId() != null, Video::getCategoryId, req.getCategoryId())
                .eq(req.getVip() != null, Video::getVip, req.getVip()) //添加是否为免费视频判断条件
                .eq(req.getActressId() != null, Video::getActressId, req.getActressId()) //添加女优id的搜索
                .eq(Video::getShortVideo, false)
                .like(StrUtil.isNotBlank(req.getTitle()), Video::getTitle, req.getTitle())
                .orderByDesc(Video::getCreateTime)
                .page(req.getPage());
        page.getRecords().forEach(v -> {
            if (v.getSource() == 0) {
                v.setUrl(null);
            }
            // 获取收藏数量
            Favorites favorites = new Favorites();
            favorites.setVideoId(v.getId());
            long favoritesCount = favoritesService.count(new QueryWrapper<>(favorites));
            v.setFavoritesCount(favoritesCount > 10000 ? UnitConvertUtils.toTenThousandUnit(favoritesCount) : StrUtil.toString(favoritesCount));
            // 获取点赞数量
            Likes likes = new Likes();
            likes.setVideoId(v.getId());
            long likesCount = likesService.count(new QueryWrapper<>(likes));
            v.setLikesCount(likesCount > 10000 ? UnitConvertUtils.toTenThousandUnit(likesCount) : StrUtil.toString(likesCount));
        });
        return Result.success(page);
    }

    /**
     * 视频详情页接口
     *
     * @param id 视频编号
     * @return 返回结果
     */
    @GetMapping("/{id}")
    public Result<Map<String, Object>> info(@PathVariable long id) {
        long userId = CurrentPlayerUserUtil.getUserId();
        Map<String, Object> data = videoService.videoDetail(id, userId);
        return Result.success(data);
    }

    /**
     * 排行榜接口
     *
     * @return 返回结果
     */
    @GetMapping("/rank")
    public Result<List<RankResp>> rankList() {
        List<Category> categories = categoryService.lambdaQuery()
                .eq(Category::getRanking, true)
                .orderByAsc(Category::getLevel)
                .orderByDesc(Category::getCreateTime)
                .list();
        List<RankResp> list = new ArrayList<>();
        for (Category category : categories) {
            List<Video> videos = videoService.rankList(category.getId(), 18);
            if (videos.size() > 0) {
                videos.forEach(v -> {
                    if (v.getSource() == 0) {
                        v.setUrl(null);
                    }
                });
                RankResp data = new RankResp();
                data.setCategory(category.getName());
                data.setList(videos);
                list.add(data);
            }
        }
        return Result.success(list);
    }

    /**
     * 排行（新）
     *
     * @param type 0：最新 1：播放数 2：点赞数
     * @return
     */
    @GetMapping("/rank/new")
    public Result<List<Video>> rankListNew(int type) {
        List<Video> list = new ArrayList<>();
        if (type == 0) {
            list = videoService.list(new LambdaQueryWrapper<>(new Video())
                    .eq(Video::getShortVideo, false)
                    .orderByDesc(Video::getCreateTime).last("limit 30"));
        } else if (type == 1) {
            list = videoService.listByPlayCount();
        } else if (type == 2) {
            list = videoService.listByLikeCount();
        }
        for (Video v : list) {
            // 获取收藏数量
            Favorites favorites = new Favorites();
            favorites.setVideoId(v.getId());
            long favoritesCount = favoritesService.count(new QueryWrapper<>(favorites));
            v.setFavoritesCount(favoritesCount > 10000 ? UnitConvertUtils.toTenThousandUnit(favoritesCount) : StrUtil.toString(favoritesCount));
            // 获取点赞数量
            Likes likes = new Likes();
            likes.setVideoId(v.getId());
            long likesCount = likesService.count(new QueryWrapper<>(likes));
            v.setLikesCount(likesCount > 10000 ? UnitConvertUtils.toTenThousandUnit(likesCount) : StrUtil.toString(likesCount));
        }
        return Result.success(list);
    }

    /**
     * 免费专区免登录播放视频
     *
     * @param id
     * @return
     */
    @GetMapping("/play/{id}")
    public Result<Map<String, Object>> play(@PathVariable long id) {
        Map<String, Object> data = videoService.playVideo(id);
        return Result.success(data);
    }

    @GetMapping("/play/new/{id}")
    public Result<Map<String, Object>> playNew(@PathVariable long id) {
        Map<String, Object> data = videoService.playVideoNew(id);
        return Result.success(data);
    }

    /**
     * 短视频列表
     *
     * @return
     */
    @GetMapping("/list/short")
    public Result<List<Video>> shortVideoList() {
        List<Video> list = videoService.lambdaQuery()
                .eq(Video::getShortVideo, true)
                .list();
        Long userId = CurrentPlayerUserUtil.getUserId();
        list.forEach(v -> {
            // 获取收藏数量
            Favorites favorites = new Favorites();
            favorites.setVideoId(v.getId());
            long favoritesCount = favoritesService.count(new QueryWrapper<>(favorites));
            v.setFavoritesCount(favoritesCount > 10000 ? UnitConvertUtils.toTenThousandUnit(favoritesCount) : StrUtil.toString(favoritesCount));
            // 获取点赞数量
            Likes likes = new Likes();
            likes.setVideoId(v.getId());
            long likesCount = likesService.count(new QueryWrapper<>(likes));
            v.setLikesCount(likesCount > 10000 ? UnitConvertUtils.toTenThousandUnit(likesCount) : StrUtil.toString(likesCount));
            if (userId != null) {
                favorites.setUserId(userId);
                long isFavorites = favoritesService.count(new QueryWrapper<>(favorites));
                v.setFavorites(isFavorites > 0);
                likes.setUserId(userId);
                long isLikes = likesService.count(new QueryWrapper<>(likes));
                v.setLikes(isLikes > 0);
            }
        });
        return Result.success(list);
    }

    /**
     * 检测短视频
     */
    @PostMapping("/short")
    public Result<Object> shortCheck() {
        FrontUser user = frontUserService.getById(CurrentPlayerUserUtil.getUserId());
        if (user.getWatchCountShort() > 0) {
            // 更新短视频次数
            user.setWatchCountShort(user.getWatchCountShort() - 1);
        } else {
            return Result.error("今日观看次数已达上限");
        }
        return Result.isSuccess(frontUserService.updateById(user));
    }

    /**
     * 推荐列表（随机）
     *
     * @return
     */
    @GetMapping("/recommend")
    public Result<List<Video>> recommendList() {
        return Result.success(videoService.recommendList());
    }

    /**
     * @return
     */
    @PostMapping("/short/count")
    public Result<FrontUser> shortCount() {
        Long userId = CurrentPlayerUserUtil.getUserId();
        FrontUser user = frontUserService.getById(userId);
        if (user != null) {
            if (user.getVipExpires() == null || user.getVipExpires().isBefore(LocalDateTime.now())) {
                if (user.getWatchCountShort() > 0) {
                    user.setWatchCountShort(user.getWatchCountShort() - 1);
                    frontUserService.updateById(user);
                }
            }
            return Result.success(user);
        }
        return Result.success(null);
    }
}
